Feels much more like a week 1 puzzle than the week 1 puzzles
Today was a straight "just implement the thing we're explaining" kind of day, with no tricks. I find it really hard to evaluate the difficult of those. The main difficulty may be in getting points on the main leaderboard, if you care about that; because everyone will be done so quickly.
I got part 1 wrong once because I forgot to do the thing the puzzle description explicitly takes care to mention:
Ignore newline characters when parsing the initialization sequence.
(Emphasis theirs.) I really have nobody to blame but myself, lmao.
Here's the main logic of my part 2:
let instructions = input
.split(',')
.filter_map(|s| s.trim().split_once(&['-', '='][..]));
for (label, target) in instructions {
let index = hash(label);
if target.is_empty() {
boxes[index].retain(|e| e.0 != label);
} else if let Some(lens) = boxes[index].iter_mut().find(|e| e.0 == label) {
*lens = (label, target.parse()?);
} else {
boxes[index].push((label, target.parse()?));
}
}
fn hash(s: &str) -> usize {
s.trim()
.bytes()
.fold(0, |acc, n| (acc + n as usize) * 17 % 256)
}
The only real noteworthy thing here, in my opinion, is that you don't really need to know whether you have a -
or a =
in the instruction, because the second part (target
in my code) is always an empty string when it's a -
instruction. That's why I do if target.is_empty()
rather than comparing the operator anywhere.
Wait, actually, I remembered something else. The problem statement misleads you by mentioning "Hashmap" (as a pun, but still); it's actually more efficient to store the 256 boxes in a straight array, rather than an Id => box
hashmap.